package 力扣.堆;

import java.util.*;

public class 最接近原点的k个点973 {
    public static void main(String[] args) {
//        int[][] points = {{1,3},{-2,2}};
        int[][] points = {{3,3},{5,-1},{-2,4}};
        int k = 2;
        int[][] ints = kClosest(points, k);
        System.out.println(Arrays.deepToString(ints));
    }
    public static int[][] kClosest(int[][] points, int k) {
//        HashMap<Integer, Long> hashMap = new HashMap<>();
        HashMap<Integer, Double> hashMap = new HashMap<>();
        for (int i = 0; i < points.length; i++) {
//            long de = (points[i][0] * points[i][0] + points[i][1] * points[i][1]);
            Double de = (double)(points[i][0] * points[i][0] + points[i][1] * points[i][1]);
            hashMap.put(i,de);
        }
        PriorityQueue<Integer> pq = new PriorityQueue<>(new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {//大根堆
//                return  (int)(hashMap.get(o2) - hashMap.get(o1));
                if (hashMap.get(o2) > hashMap.get(o1)){
                    return 1;
                }else {
                    return -1;
                }
            }
        });
        Set<Integer> set = hashMap.keySet();
        Iterator<Integer> iterator = set.iterator();
        while (iterator.hasNext()){
            Integer next = iterator.next();
            pq.offer(next);
            if (pq.size() > k){
                pq.poll();
            }
        }
        int[][] ans = new int[k][2];
        int i = 0;
        while (!pq.isEmpty()){
            int te = pq.poll();
            ans[i][0] = points[te][0];
            ans[i][1] = points[te][1];
            i++;
        }
        return ans;
    }
}
